# -*- coding: utf-8 -*-
# SecureCRT会话生成器

import os
from core.generator import SessionGenerator

class SecureCRTGenerator(SessionGenerator):
    """SecureCRT会话生成器"""
    
    def generate_session(self, machine, output_dir=None):
        """为单台机器生成会话文件"""
        if not self.template_content:
            return False
        
        try:
            # 参数验证
            if not isinstance(machine, dict):
                print(f"生成会话失败: 机器信息格式错误，应为字典而不是 {type(machine)}")
                return False
            
            # 提取机器信息
            machine_role = machine.get('role', '')
            machine_name = machine.get('hostname', '')
            machine_ip = machine.get('IP', '')
            machine_username = machine.get('username', '')
            machine_password = machine.get('password', '')
            
            # 必须字段检查
            if not machine_role or not machine_name or not machine_ip:
                print(f"生成会话失败: 缺少必要字段 (role={machine_role}, hostname={machine_name}, IP={machine_ip})")
                return False
            
            # 处理模板替换
            templines = self.template_content.splitlines()
            machine_session = []
            
            for line in templines:
                if line.startswith('Host'):
                    line = f'Host={machine_ip}'
                elif line.startswith('UserName'):
                    line = f'UserName={machine_username}'
                elif line.startswith('Password'):
                    line = f'Password={machine_password}'
                machine_session.append(line)
            
            # 获取角色目录路径
            role_dir = self.get_output_path('securecrt', output_dir, machine_role)
            print(f"SecureCRT会话将保存到: {role_dir}")
            
            # 检查目录是否可写
            if not self.check_directory_writeable(role_dir):
                print(f"无法写入目录: {role_dir}")
                return False
            
            # 保存会话文件
            session_file = os.path.join(role_dir, f'{machine_name}-{machine_ip}.ini')
            with open(session_file, 'w', encoding='utf-8') as f:
                f.write('\n'.join(machine_session))
            
            print(f"已生成SecureCRT会话文件: {session_file}")
            return True
            
        except Exception as e:
            import traceback
            print(f"生成SecureCRT会话失败: {e}")
            print(f"详细错误: {traceback.format_exc()}")
            return False

    def generate_all_sessions(self, data_path, output_dir=None, sheet_name='Sheet1'):
        """生成所有SecureCRT会话文件"""
        if not self.template_content:
            print("错误: 模板文件未加载")
            return False
        
        # 加载数据
        machines, error = self.load_data(data_path, sheet_name)
        if error:
            print(f"加载数据文件失败: {error}")
            return False
        
        if not machines or len(machines) == 0:
            print("错误: 机器列表为空")
            return False
        
        # 为每台机器生成会话文件
        success_count = 0
        total_count = len(machines)
        
        print(f"开始生成 {total_count} 个SecureCRT会话文件...")
        
        for idx, machine in enumerate(machines, 1):
            print(f"正在处理 SecureCRT 会话 {idx}/{total_count}：{machine.get('hostname', '未知')}")
            if self.generate_session(machine, output_dir):
                success_count += 1
        
        base_dir = os.path.join(output_dir if output_dir else os.getcwd(), 'sessions', 'securecrt')
        print(f"已成功生成 {success_count}/{total_count} 个SecureCRT会话文件，保存在 {base_dir}")
        
        if success_count == 0:
            print("警告: 没有生成任何SecureCRT会话文件，请检查以下可能的原因:")
            print("  1. 机器列表中角色字段拼写是否正确")
            print("  2. 是否缺少必要字段: hostname, IP, role")
            print("  3. 是否有权限写入输出目录")
        
        return success_count > 0 